package com.ljx.rabbit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljx.rabbit.context.BaseContext;
import com.ljx.rabbit.domain.dto.AddCartDTO;
import com.ljx.rabbit.domain.dto.ItemCommentDTO;
import com.ljx.rabbit.domain.dto.OrderDTO;
import com.ljx.rabbit.domain.dto.OrderPageDTO;
import com.ljx.rabbit.domain.po.*;
import com.ljx.rabbit.domain.vo.OrderPageVo;
import com.ljx.rabbit.domain.vo.OrderVO4Page;
import com.ljx.rabbit.domain.vo.SkuOrder4Page;
import com.ljx.rabbit.mapper.*;
import com.ljx.rabbit.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-07
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    private final SkuOrderMapper skuOrderMapper;
    private final SkusMapper skusMapper;
    private final UserMapper userMapper;
    private final CartMapper cartMapper;
    private final ItemMapper itemMapper;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Order submitOrder(OrderDTO orderDTO) {
        Order order=new Order();
        BeanUtils.copyProperties(orderDTO,order);
        order.setCreateTime(LocalDateTime.now());
        order.setPayEnd(LocalDateTime.now().plusMinutes(15));
        order.setUserId(BaseContext.getCurrentId());
        List<AddCartDTO> goods = orderDTO.getGoods();
        BigDecimal payMoney = new BigDecimal(0);
        Integer totalNum = 0;
        for (AddCartDTO good : goods) {
            Skus skus = skusMapper.selectById(good.getSkuId());
            BigDecimal price = new BigDecimal(skus.getPrice());
            payMoney = price.multiply(new BigDecimal(good.getCount())).add(payMoney);
            totalNum += good.getCount();
        }
        BigDecimal totalMoney = payMoney.add(new BigDecimal(orderDTO.getPostFee()));
        order.setPayMoney(String.valueOf(payMoney));
        order.setTotalMoney(String.valueOf(totalMoney));
        order.setTotalNum(totalNum);

        save(order);

        Long orderId = order.getId();
        List<SkuOrder> skuOrders = goods.stream().map(item -> {
            SkuOrder skuOrder=new SkuOrder();
            skuOrder.setOrderId(orderId);
            skuOrder.setSkusId(item.getSkuId());
            skuOrder.setCount(item.getCount());
            return skuOrder;
        }).collect(Collectors.toList());
        skuOrderMapper.insert(skuOrders);

        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(Cart::getId,orderDTO.getCartIds());
        cartMapper.update(new Cart().setShown(false).setOrderId(orderId), wrapper);
        return order;
    }

    @Override
    @Transactional
    public void payOrder(Long orderId) {
        User user = userMapper.selectById(BaseContext.getCurrentId());
        if (user.getBalance().compareTo(new BigDecimal(getById(orderId).getTotalMoney()))<0){
            throw new RuntimeException("余额不足");
        }
        user.setBalance(user.getBalance().subtract(new BigDecimal(getById(orderId).getTotalMoney())));
        userMapper.updateById(user);
        updateById(new Order().setOrderState(2).setPayTime(LocalDateTime.now()).setId(orderId));
    }

    @Override
    public OrderPageVo getOrderPage(OrderPageDTO params) {
        Page<Order> page = new Page<>(params.getPage(), params.getPageSize());
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Order::getUserId,BaseContext.getCurrentId()).orderByDesc(Order::getCreateTime);
        if(params.getOrderState()!=0){//不是全选
            queryWrapper.lambda().eq(Order::getOrderState,params.getOrderState());
        }
        page(page,queryWrapper);
        List<Order> orders=page.getRecords();
        if(orders.size()==0){
            return new OrderPageVo();
        }
        OrderPageVo orderPageVo = new OrderPageVo();
        long total = page.getTotal();
        List<OrderVO4Page> items = new ArrayList<>();
        for (Order order : orders) {
            OrderVO4Page orderVO4Page = new OrderVO4Page();
            BeanUtils.copyProperties(order,orderVO4Page);

            Duration duration = Duration.between(LocalDateTime.now(), order.getPayEnd());
            long seconds = duration.getSeconds();
            System.out.println("时间差（秒）: " + seconds);
            orderVO4Page.setCountdown(seconds);

            List<Cart> list=cartMapper.selectList(new QueryWrapper<Cart>().lambda().eq(Cart::getOrderId,order.getId()));
            List<SkuOrder4Page> skus = new ArrayList<>();
            for (Cart cart : list) {
                SkuOrder4Page skuOrder4Page = new SkuOrder4Page();
                BeanUtils.copyProperties(cart,skuOrder4Page);
                BigDecimal price = new BigDecimal(cart.getPrice());
                BigDecimal count = new BigDecimal(cart.getCount());
                skuOrder4Page.setImage(cart.getPicture());
                skuOrder4Page.setRealPay(String.valueOf(price.multiply(count)));
                skus.add(skuOrder4Page);
            }
            orderVO4Page.setSkus(skus);
            items.add(orderVO4Page);
        }
        orderPageVo.setCounts(total);
        orderPageVo.setItems(items);
        return orderPageVo;
    }

    @Override
    public void cancelOrder(Long orderId) {
        updateById(new Order().setOrderState(6).setId(orderId));
    }

    @Override
    public void delById(Long orderId) {
        //删除对应cart
        cartMapper.delete(new QueryWrapper<Cart>().lambda().eq(Cart::getOrderId,orderId));
        //删除对应skuOrder
        skuOrderMapper.delete(new QueryWrapper<SkuOrder>().lambda().eq(SkuOrder::getOrderId,orderId));
        //删除order
        removeById(orderId);
    }

    @Override
    public void confirmOrder(Long orderId) {
        Order order = getById(orderId);
        if(order.getOrderState().equals(3))
            updateById(order.setOrderState(4));
        else
            throw new RuntimeException("订单状态错误");
    }

    @Override
    public void commentItem(ItemCommentDTO itemCommentDTO) {
        Comment comment=new Comment();
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        BeanUtils.copyProperties(itemCommentDTO,comment);
        comment.setUserId(userId);
        comment.setCreateTime(LocalDateTime.now());
        comment.setAvatar(user.getAvatar());
        comment.setNickname(user.getNickname());
        mongoTemplate.save(comment);
        updateById(new Order().setOrderState(5).setId(itemCommentDTO.getOrderId()));
        Item item = itemMapper.selectById(itemCommentDTO.getItemId());
        itemMapper.update(new Item().setCommentCount(item.getCommentCount()+1),new QueryWrapper<Item>().lambda().eq(Item::getId,itemCommentDTO.getItemId()));
    }
}
